<template>
  <div class="membership-discounts-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">会员卡折扣</h1>
      <p class="page-description">
        为不同会员卡设置不同类型商品的特殊折扣，满足医院差异化定价需求
      </p>
    </div>

    <!-- 会员卡类型标签页 -->
    <div class="card-tabs">
      <a-tabs
        v-model:activeKey="selectedCardType"
        @change="handleCardTypeChange"
      >
        <a-tab-pane key="gold" tab="金卡" />
        <a-tab-pane key="silver" tab="银卡" />
        <a-tab-pane key="normal" tab="普通卡" />
      </a-tabs>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <div class="left-actions">
        <a-button type="primary" @click="showBatchDiscountModal">
          <template #icon><UserRoundPen /></template>
          批量修改特殊折扣
        </a-button>
      </div>
      <div class="right-actions">
        <a-select
          v-model:value="discountFilter"
          placeholder="折扣筛选"
          style="width: 150px"
          @change="handleDiscountFilterChange"
        >
          <a-select-option value="all">全部折扣</a-select-option>
          <a-select-option value="special">特殊折扣</a-select-option>
          <a-select-option value="default">默认折扣</a-select-option>
        </a-select>
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="名称/编号/条形码"
          style="width: 250px"
          @search="handleSearch"
        />
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧筛选区域 -->
      <div class="filter-sidebar">
        <!-- 商品分类 -->
        <div class="filter-section">
          <h3 class="filter-title">商品分类</h3>
          <div class="filter-list">
            <div
              v-for="category in categories"
              :key="category.id"
              :class="[
                'filter-item',
                { active: selectedCategory === category.id },
              ]"
              @click="selectCategory(category.id)"
            >
              {{ category.name }}
            </div>
          </div>
        </div>

        <!-- 目录 -->
        <div class="filter-section">
          <h3 class="filter-title">目录</h3>
          <div class="filter-list">
            <div
              v-for="directory in directories"
              :key="directory.id"
              :class="[
                'filter-item',
                { active: selectedDirectory === directory.id },
              ]"
              @click="selectDirectory(directory.id)"
            >
              {{ directory.name }}
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧商品列表 -->
      <div class="products-content">
        <div class="products-table">
          <a-table
            :columns="columns"
            :data-source="filteredProducts"
            :pagination="pagination"
            :row-selection="rowSelection"
            :loading="loading"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'specialDiscount'">
                <div class="discount-cell">
                  <span class="discount-value">{{
                    record.specialDiscount || '0.00'
                  }}</span>
                  <a-button
                    type="link"
                    size="small"
                    @click="showIndividualDiscountModal(record)"
                  >
                    <template #icon><UserRoundPen /></template>
                    ∠
                  </a-button>
                </div>
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </div>

    <!-- 批量修改折扣模态框 -->
    <BatchDiscountModal
      v-model:visible="batchDiscountModalVisible"
      :selectedProducts="selectedProducts"
      :cardType="selectedCardType"
      @save="handleBatchDiscountSave"
    />

    <!-- 单独修改折扣模态框 -->
    <IndividualDiscountModal
      v-model:visible="individualDiscountModalVisible"
      :product="currentProduct"
      :cardType="selectedCardType"
      @save="handleIndividualDiscountSave"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import type { TableProps } from 'ant-design-vue';
import { UserRoundPen } from '@vben/icons';

import BatchDiscountModal from './components/BatchDiscountModal.vue';
import IndividualDiscountModal from './components/IndividualDiscountModal.vue';

// 响应式数据
const loading = ref(false);
const selectedCardType = ref('gold');
const selectedCategory = ref('all');
const selectedDirectory = ref('all');
const discountFilter = ref('all');
const searchKeyword = ref('');
const selectedProducts = ref<string[]>([]);
const currentProduct = ref<any>(null);

// 模态框控制
const batchDiscountModalVisible = ref(false);
const individualDiscountModalVisible = ref(false);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 商品分类数据
const categories = ref([
  { id: 'all', name: '全部' },
  { id: 'registration', name: '挂号' },
  { id: 'prescription', name: '处方' },
  { id: 'inspection', name: '检验' },
  { id: 'imaging', name: '影像' },
  { id: 'treatment', name: '处置' },
  { id: 'surgery', name: '手术' },
  { id: 'hospitalization', name: '住院' },
  { id: 'boarding', name: '寄养' },
  { id: 'vaccine', name: '疫苗' },
  { id: 'deworming', name: '驱虫' },
  { id: 'beauty', name: '美容' },
]);

// 目录数据
const directories = ref([
  { id: 'all', name: '全部' },
  { id: 'outpatient', name: '门诊' },
  { id: 'internal', name: '内科用药' },
  { id: 'food', name: '粮食' },
  { id: 'dog', name: '犬用' },
  { id: 'cat', name: '猫用' },
  { id: 'vaccine-service', name: '疫苗服务' },
  { id: 'internal-deworming', name: '内驱' },
  { id: 'external-deworming', name: '外驱' },
  { id: 'package', name: '套餐' },
]);

// 商品数据
const products = ref([
  {
    id: '1',
    code: 'P000000001',
    barcode: '123456789',
    name: '健胃消食片',
    specification: '0.5g*24片',
    unit: '盒',
    unitPrice: 25.0,
    category: 'prescription',
    directory: 'internal',
    specialDiscount: 0,
    participateDiscount: true,
  },
  {
    id: '2',
    code: 'P000000002',
    barcode: '123456790',
    name: '猫粮',
    specification: '2kg',
    unit: '袋',
    unitPrice: 80.0,
    category: 'food',
    directory: 'cat',
    specialDiscount: 9.0,
    participateDiscount: true,
  },
  {
    id: '3',
    code: 'P000000003',
    barcode: '123456791',
    name: '美容服务',
    specification: '标准套餐',
    unit: '次',
    unitPrice: 120.0,
    category: 'beauty',
    directory: 'outpatient',
    specialDiscount: 8.0,
    participateDiscount: true,
  },
  {
    id: '4',
    code: 'P000000004',
    barcode: '123456792',
    name: '疫苗注射',
    specification: '三联疫苗',
    unit: '支',
    unitPrice: 60.0,
    category: 'vaccine',
    directory: 'vaccine-service',
    specialDiscount: 0,
    participateDiscount: true,
  },
]);

// 表格列定义
const columns: TableProps['columns'] = [
  {
    title: '编号',
    dataIndex: 'code',
    key: 'code',
    width: 120,
  },
  {
    title: '条形码',
    dataIndex: 'barcode',
    key: 'barcode',
    width: 120,
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '规格',
    dataIndex: 'specification',
    key: 'specification',
    width: 150,
  },
  {
    title: '单位',
    dataIndex: 'unit',
    key: 'unit',
    width: 80,
  },
  {
    title: '单价',
    dataIndex: 'unitPrice',
    key: 'unitPrice',
    width: 100,
    align: 'right',
    customRender: ({ text }) => `¥${text?.toFixed(2) || '0.00'}`,
  },
  {
    title: '特殊折扣设置',
    key: 'specialDiscount',
    width: 150,
    align: 'center',
  },
];

// 计算属性
const filteredProducts = computed(() => {
  let filtered = products.value.filter((product) => {
    // 分类筛选
    if (
      selectedCategory.value !== 'all' &&
      product.category !== selectedCategory.value
    ) {
      return false;
    }
    // 目录筛选
    if (
      selectedDirectory.value !== 'all' &&
      product.directory !== selectedDirectory.value
    ) {
      return false;
    }
    // 折扣筛选
    if (discountFilter.value === 'special' && !product.specialDiscount) {
      return false;
    }
    if (discountFilter.value === 'default' && product.specialDiscount) {
      return false;
    }
    // 搜索筛选
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase();
      return (
        product.name.toLowerCase().includes(keyword) ||
        product.code.toLowerCase().includes(keyword) ||
        product.barcode.toLowerCase().includes(keyword)
      );
    }
    return true;
  });

  // 更新分页总数
  pagination.total = filtered.length;

  return filtered;
});

// 表格行选择配置
const rowSelection = reactive({
  selectedRowKeys: selectedProducts,
  onChange: (keys: string[]) => {
    selectedProducts.value = keys;
  },
});

// 方法
const handleCardTypeChange = (key: string) => {
  selectedCardType.value = key;
  selectedProducts.value = [];
};

const selectCategory = (categoryId: string) => {
  selectedCategory.value = categoryId;
  selectedProducts.value = [];
};

const selectDirectory = (directoryId: string) => {
  selectedDirectory.value = directoryId;
  selectedProducts.value = [];
};

const handleDiscountFilterChange = () => {
  selectedProducts.value = [];
};

const handleSearch = () => {
  selectedProducts.value = [];
};

// 模态框显示函数
const showBatchDiscountModal = () => {
  if (selectedProducts.value.length === 0) {
    message.warning('请先选择要修改的商品');
    return;
  }
  batchDiscountModalVisible.value = true;
};

const showIndividualDiscountModal = (product: any) => {
  currentProduct.value = { ...product };
  individualDiscountModalVisible.value = true;
};

// 保存处理函数
const handleBatchDiscountSave = (discount: number) => {
  selectedProducts.value.forEach((productId) => {
    const product = products.value.find((p) => p.id === productId);
    if (product) {
      product.specialDiscount = discount;
    }
  });
  message.success('批量修改成功');
  batchDiscountModalVisible.value = false;
  selectedProducts.value = [];
};

const handleIndividualDiscountSave = (productId: string, discount: number) => {
  const product = products.value.find((p) => p.id === productId);
  if (product) {
    product.specialDiscount = discount;
  }
  message.success('修改成功');
  individualDiscountModalVisible.value = false;
};

// 页面初始化
onMounted(() => {
  loading.value = false;
});
</script>

<style scoped>
.membership-discounts-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.page-header {
  background: white;
  padding: 24px;
  border-bottom: 1px solid #e8e8e8;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.page-description {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.card-tabs {
  background: white;
  padding: 0 24px;
  border-bottom: 1px solid #e8e8e8;
}

.action-bar {
  background: white;
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e8e8e8;
}

.left-actions {
  display: flex;
  gap: 8px;
}

.right-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.filter-sidebar {
  width: 250px;
  background: white;
  border-right: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.filter-section {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.filter-title {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.filter-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.filter-item {
  padding: 8px 12px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
  font-size: 14px;
}

.filter-item:hover {
  background-color: #f5f5f5;
}

.filter-item.active {
  background-color: #e6f7ff;
  color: #1890ff;
}

.products-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.products-table {
  flex: 1;
  overflow: hidden;
  background: white;
}

.discount-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.discount-value {
  font-weight: 500;
  color: #1890ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .right-actions {
    justify-content: center;
  }

  .main-content {
    flex-direction: column;
  }

  .filter-sidebar {
    width: 100%;
    height: 200px;
  }
}
</style>
